package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;


import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;

import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;

import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.service.*;

import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import com.tanhua.server.vo.UserInformation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanHuaServiceImpl implements TanHuaService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionService questionService;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    @Value("${tanhua.default.recommend.users}")
    private String defaultRecommendUsers;

    /**
     * 查看个人信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInformation queryUserInfo(Long userId) {
        User user = UserThreadLocal.get();

        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInformation userInformation = new UserInformation();
        userInformation.setId(userId);
        userInformation.setAge(userInfo.getAge());
        userInformation.setGender(userInfo.getSex().name().toLowerCase());
        userInformation.setNickname(userInfo.getNickName());
        userInformation.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
        userInformation.setAvatar(userInfo.getLogo());
        /*#表结构，表名：recommend_user
        {
            "userId":1001,  #推荐的用户id
            "toUserId":1002, #用户id
            "score":90,  #推荐得分
            "date":"2019/1/1" #日期
        }*/
        //缘分值
        Double score = this.recommendUserService.queryScore(user.getId(), userId);
        userInformation.setFateValue(score.longValue());

        //记录来访用户
        this.visitorsApi.saveVisitor(userId, user.getId(), "个人主页");

        return userInformation;
    }

    /**
     * 查看陌生人问题
     *
     * @param userId
     * @return
     */
    @Override
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (ObjectUtil.isNotEmpty(question)) {
            return question.getTxt();
        }
        return null;
    }

    /**
     * 回复陌生人信息
     *
     * @param userId 陌生人的userId
     * @param reply  回复的消息
     * @return
     */
    @Override
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());
        //构建环信消息

        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);

        Boolean flag = this.huanXinApi.sendMsgFromAdmin("HX_" + userId,
                HuanXinMessageType.TXT,
                JSONUtil.toJsonStr(msg));
        System.out.println(flag);
        return flag;
    }

    /**
     * 搜索附近的人
     *
     * @param gender
     * @param distance
     * @return
     */
    @Override
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)) {
            return ListUtil.empty();
        }

        PageInfo<UserLocationVo> pageInfo = this.userLocationApi.queryUserFromLocation(
                userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance),
                1,
                50);

        List<UserLocationVo> userLocationVoList = pageInfo.getRecords();
        if (CollUtil.isEmpty(userLocationVoList)) {
            return ListUtil.empty();
        }

        //构建筛选条件

        List<Object> userIdList = CollUtil.getFieldValues(userLocationVoList, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        //比较字符串是否相等，比较的时候忽略大小写
        if (StrUtil.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else if (StrUtil.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<NearUserVo> nearUserVoList = new ArrayList<>();
        NearUserVo nearUserVo;
        for (UserLocationVo locationVo : userLocationVoList) {
            //排除自己
            if (ObjectUtil.equals(locationVo.getUserId(), user.getId())) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(locationVo.getUserId(), userInfo.getUserId())) {
                    nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }

        }

        return nearUserVoList;
    }

    /**
     * 查询推荐卡片列表，从推荐列表中随机选取10个用户
     *
     * @return
     */
    @Override
    public List<UserInformation> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;

        //查询到的50条数据，并不是用来直接展现，需要从这50条数据中随机返回一些数据
        List<RecommendUser> recommendUserList = this.recommendUserService.queryCardList(user.getId(), count);
        if (CollUtil.isEmpty(recommendUserList)) {
            //推荐为空时  使用默认推荐
            recommendUserList = new ArrayList<>();
            List<String> list = StrUtil.split(defaultRecommendUsers, ',');
            RecommendUser recommendUser;
            for (String id : list) {
                recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(id));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);
            }
        }
        //计算展现的数量，默认展现10个,当查询到的推荐人数小于10，展示查询到的人
        int showCount = Math.min(10, recommendUserList.size());

        List<RecommendUser> result = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //TODO 可能重复
            int index = RandomUtil.randomInt(0, recommendUserList.size());
            RecommendUser recommendUser = recommendUserList.get(index);
            result.add(recommendUser);

        }
        List<Object> userIdList = CollUtil.getFieldValues(result, "toUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        List<UserInformation> userInformationList = new ArrayList<>();
        UserInformation userInformation;
        for (UserInfo userInfo : userInfoList) {
            userInformation = new UserInformation();
            userInformation.setId(userInfo.getUserId());
            userInformation.setAge(userInfo.getAge());
            userInformation.setAvatar(userInfo.getLogo());
            userInformation.setGender(userInfo.getSex().name().toLowerCase());
            userInformation.setNickname(userInfo.getNickName());
            userInformation.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            userInformation.setFateValue(0L);

            userInformationList.add(userInformation);
        }
        return userInformationList;
    }

    /**
     * 左滑右滑-喜欢
     *
     * @param likeUserId
     * @return
     */
    @Override
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = this.userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result){
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)){
            this.imService.contactUser(likeUserId);
        }

        return true;
    }

    /**
     * 左滑右滑-喜欢
     *
     * @param likeUserId
     * @return
     */
    @Override
    public Boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = this.userLikeApi.notLikeUser(user.getId(), likeUserId);
        return result;
    }
}
